import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/task/scheduling_config_entity.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/security_all_fundamentals_page/clock_in/clock_in_controller.dart';
import 'package:get/get.dart';
import 'package:jiffy/jiffy.dart';

class CheckInController extends GetxController {
  ///外部列表controller
  final listController = Get.find<ClockInController>();

  /// app打卡状态：1-上班卡 2-下班卡 3-请假
  int appClockStatus = Get.arguments['appClockStatus'] as int;

  /// 当前时间
  String currentTime = '';

  /// 输入的原因
  String reason = '';

  /// 当前选中计划
  late SchedulingConfigEntity currentPlan; // = Get.arguments['entity'] as SchedulingConfigEntity;

  @override
  void onInit() {
    super.onInit();
    currentPlan = listController.currentPlan;
    setCurrentTime();
  }

  /// 设置当前时间
  void setCurrentTime() {
    currentTime = Jiffy.parseFromDateTime(DateTime.now()).format(pattern: 'yyyy-MM-dd HH:mm:ss');
  }

  /// 获取标题
  String getTitle() {
    switch (appClockStatus) {
      case 1:
        return '上班打卡';
      case 2:
        return '下班打卡';
      case 3:
        return '请假';
      default:
        return '';
    }
  }

  /// 提交
  Future<void> submit() async {
    setCurrentTime();
    // if (reason.isEmpty) {
    //   AppToast.showWarning('请输入${appClockStatus == 3 ? '请假原因' : '值班记录'}!');
    //   return;
    // }
    if (reason.isEmpty && appClockStatus == 3) {
      AppToast.showWarning('请输入请假原因');
      return;
    }
    // 填入原因
    if (reason.isNotEmpty) {
      if (appClockStatus == 3) {
        currentPlan.askForLeave = reason;
      } else {
        currentPlan.clockInRemark = reason;
      }
    }
    // 设置状态
    currentPlan.appClockStatus = appClockStatus;
    switch (appClockStatus) {
      // 上班打卡
      case 1:
        currentPlan.classesBeginDateRecord = currentTime;
        break;
      // 下班打卡
      case 2:
        currentPlan.classesEndDateRecord = currentTime;
        break;
      // 请假
      case 3:
        break;
    }

    // 调用打卡接口
    final res = await HttpUtil().generatePostRequest(Interface.upSchedulingConfigPlanRecord, data: currentPlan.toJson()).execute();
    res.onSuccess((result) {
      listController.update();
      Get.back();
    });
    res.onError((result) {
      withdrawData();
    });
  }

  /// 失败撤回数据
  void withdrawData() {
    // 填入原因
    if (appClockStatus == 3) {
      currentPlan.askForLeave = '';
    } else {
      currentPlan.clockInRemark = '';
    }
    // 设置状态
    currentPlan.appClockStatus = 0;
    switch (appClockStatus) {
      // 上班打卡
      case 1:
        currentPlan.classesBeginDateRecord = '';
        break;
      // 下班打卡
      case 2:
        currentPlan.classesEndDateRecord = '';
        break;
      // 请假
      case 3:
        break;
    }
  }
}
